<?php

namespace App\Http\Controllers\Company;

use App\Http\Controllers\Controller;
use App\Models\ClassCourseModel;
use Illuminate\Http\Request;
use App\Models\ClassModel;
use App\Models\CourseArrangeModel;
use App\Models\ClassStudentModel;

class ClassController extends Controller
{
    public function list(Request $request){
        $data = ClassModel::where('company_id', $request->company_id)->orderBy('id', 'desc')->get();
        return self::sendOk($data);
    }
    
    public function page(Request $request){
        $name = $request->name;
        $teacherId = $request->teacher_id;
        $query = ClassModel::where('company_id', $request->company_id)->with('courses');
        if ($name)
            $query->where('name', 'like', '%'.$name.'%');
        
        if ($teacherId){
            $classIds = ClassCourseModel::where('teacher_id', $teacherId)->pluck('class_id');
            $query->whereIn('id', $classIds);
        }
            
        
        $data = $query->orderBy('id', 'desc')->paginate(15, ['*'], 'page', $request->page);
        return self::sendOk($data);
    }

    public function add(Request $request){
        $class = new ClassModel();
        $class->fill($request->all());
        $class->save();
        return self::sendOk($class);
    }

    public function edit(Request $request){
        $class = ClassModel::find($request->id);
        if ($class->company_id != $request->company_id){
            return self::sendError('非法操作');
        }
        $class->fill($request->all());
        $class->save();
        return self::sendOk($class);
    }

    public function delete(Request $request){
        $class = ClassModel::find($request->id);
        if ($class->company_id!= $request->company_id){
            return self::sendError('非法操作');
        }
        $class->delete(); //0.删除班级信息
        CourseArrangeModel::where('class_id', $request->id)->delete(); // 1.删除排课信息
        ClassStudentModel::where('class_id', $request->id)->delete(); // 2.删除班级下的学员信息
        ClassCourseModel::where('class_id', $request->id)->delete(); // 3.删除班级下的课程信息
        return self::sendOk();
    }
}
